package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.*;
import cn.wolfcode.feign.AlipyFeignApi;
import cn.wolfcode.feign.IntergralFeignApi;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private AlipyFeignApi alipyFeignApi;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IntergralFeignApi intergralFeignApi;


    @RequestMapping("alipay")
    public Result<String> alipay(String orderNo,int type){
        // 参数校验
        if (StringUtils.isEmpty(orderNo)) {
            throw new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }

        // 查询订单
        OrderInfo orderInfo = orderInfoService.findByOderNo(orderNo);
        if (orderInfo == null){
            throw new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }

        String result = null;
        // 根据 type 类型判断是 支付宝支付 还是 积分支付
        if (OrderInfo.PAYTYPE_ONLINE.equals(type)){
            // 支付宝支付 => 返回支付界面的 josn 数据
            result = orderInfoService.payOnline(orderNo);
        }else {
            // 积分支付
           result =  orderInfoService.payOnIntergral(orderNo);
        }
        return Result.success(result);
    }

    // 同步回调 --> 支付流程结束之后返回页面
    @RequestMapping("return_url")
    public void returnUrl(@RequestParam Map<String,String> params, HttpServletResponse response) throws IOException {
        // 获取订单编号
        String orderNo = params.get("out_trade_no");

        // 远程调用支付宝接口 进行验签操作
        Result<Boolean> result = alipyFeignApi.checkSign(params);
        if (result != null && !result.hasError()){
            if (result.getData()){
                response.sendRedirect(frontEndPayUrl + orderNo);
            }else {
                response.sendRedirect("http://localhost/50x.html");
            }
        }
    }

    // 异步回调  --> 修改订单
    @RequestMapping("notify_url")
    public void notifyUrl(@RequestParam Map<String,String> params, HttpServletResponse response) throws IOException {
        // 获取订单编号
        String orderNo = params.get("out_trade_no");

        PrintWriter out = response.getWriter();

        // 远程调用支付宝接口 进行验签操作
        Result<Boolean> result = alipyFeignApi.checkSign(params);
        if (result != null && !result.hasError()){
            if (result.getData()){
                // 支付成功订单逻辑
                orderInfoService.paySuccess(orderNo);
                // 修改订单状态
               orderInfoService.changePayStatus(orderNo,OrderInfo.STATUS_ACCOUNT_PAID,OrderInfo.PAYTYPE_ONLINE);
               // 实现支付成功逻辑
               out.write("success");
            }else {
                // 验证失败
                out.write("fail");
            }
        }

    }


    // 申请退款
    @RequestMapping("refund")
    public String refund(String orderNo) {
        // 参数校验
        if (StringUtils.isEmpty(orderNo)) {
            throw  new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }

        // 查询对应订单
        OrderInfo orderInfo = orderInfoService.findByOderNo(orderNo);
        if (orderInfo == null){
            throw new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }

        // 查看是 在线支付还是 积分支付
        if (OrderInfo.PAYTYPE_ONLINE.equals(orderInfo.getPayType())){
            // 支付宝支付 退款
            orderInfoService.refundOnline(orderNo);

        }else if (OrderInfo.PAYTYPE_INTERGRAL.equals(orderInfo.getPayType())){
            // 积分支付 => 使用 seata 的TCC控制分布式事务
            orderInfoService.refundIntergral(orderNo);
        }
        return "";

    }


}
